package com.zhaopin.thread;

import java.util.concurrent.CountDownLatch;

/**
 * @author Administrator
 * @create 2021-03-30 9:39
 */
public class TestLatch {
    /**
     * mCountDownLatch默认计数器是2
     */
    private final static CountDownLatch mCountDownLatch = new CountDownLatch(2);

    /**
     * 示例工作线程类
     */
    private static class WorkingThread extends Thread {
        private final String mThreadName;
        private final int mSleepTime;

        public WorkingThread(String name, int sleepTime) {
            mThreadName = name;
            mSleepTime = sleepTime;
        }

        @Override
        public void run() {
            System.out.println("[" + mThreadName + "] started!");
            try {
                Thread.sleep(mSleepTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            mCountDownLatch.countDown();
            System.out.println("[" + mThreadName + "] end!");
        }
    }

    /**
     * 示例线程类
     */
    private static class SampleThread extends Thread {

        @Override
        public void run() {
            System.out.println("[SampleThread] started!");
            try {
                // mCountDownLatch会导致SampleThread线程阻塞在这里等待，直到另外的WorkingThread调用countDown()把mCountDownLatch 里的count变为0，然后SampleThread才能够继续往下执行；
                mCountDownLatch.await();
            } catch (InterruptedException e) {

            }
            System.out.println("[SampleThread] end!");
        }
    }

    public static void main(String[] args) throws Exception {
        // 最先run SampleThread
//        new SampleThread().start();
//        // 运行两个工作线程
//        new WorkingThread("WorkingThread1", 2000).start();
//        new WorkingThread("WorkingThread2", 2000).start();
        System.out.println(Math.random());
    }
}
